from flask import Flask, request
import smtplib
from email.mime.text import MIMEText
import pymongo
import time
import threading

app = Flask(__name__)


@app.route('/sendmail', methods=['POST'])
def deal_with_post():
	From = '1019798632@qq.com'
	Tolist = list()
	Tolist.append(request.form['to'])
	Text = request.form['contents']
	Message = MIMEText(Text, 'plain', 'utf-8')
	Message['Subject'] = request.form['contents'][0:5]

	send_mail_thread = mail_thread(From, Tolist, Message)
	send_mail_thread.start()

	mani_db_thread = db_thread(From, Tolist)
	mani_db_thread.start()
	return 'send successful'

@app.route('/transfer', methods=['POST'])
def transfer():
    request_data = request.form.to_dict()
    print request_data
    return 'yeah'


class mail_thread(threading.Thread):

	def __init__(self, fromaddr, tolist, message):
		threading.Thread.__init__(self)
		self.fromaddr = fromaddr
		self.tolist = tolist
		self.message = message

	def run(self):
		print 'sending mail start'
		sendmail(self.fromaddr, self.tolist, self.message)

def sendmail(fromaddr, tolist, message):
	server = smtplib.SMTP('smtp.qq.com:25')
	server.login('1019798632@qq.com', 'sandy930707')
	server.sendmail(fromaddr, tolist, message.as_string())
	server.quit()

class db_thread(threading.Thread):

	def __init__(self, fromaddr, tolist):
		threading.Thread.__init__(self)
		self.fromaddr = fromaddr
		self.tolist = tolist

	def run(self):
		print 'Manipulating database...'
		manipu_db(self.fromaddr, self.tolist)

def manipu_db(From, Tolist):
	myclient = pymongo.MongoClient(host='localhost', port=27017)
	db = pymongo.database.Database(myclient, 'test')
	# db has a collectoin named 'maillog', you can access it by db.maillog or db['maillog']
	db.maillog.insert_one({
		'from': From,
		'to': Tolist[0],
		'time': time.ctime()
		})
	myclient.close()


if __name__ == '__main__':
	app.run(debug=True)